import { mapState, mapMutations } from 'vuex';
export default {
	data() {
		return {		
		}
	},
    computed: {
        ...mapState(['globalConfig', 'hasLogin'])
    },
    methods: {
        waitVariable: function (name) {
            var vm = this;
            if (!global.waitObj[name]) {
                global.waitObj[name] = 1;
            } else {
                global.waitObj[name]++;
            }
            return new Promise((resolve, reject) => {
                var v = vm[name];
                if (!v) {
                    if (global.waitObj[name] > 100) {
                        reject();
                        return;
                    }
                    console.log('等待变量', name);
                    setTimeout(() => {
                        v = vm.waitVariable(name);
                        resolve(v);
                    }, 200)
                } else {
                    global.waitObj[name] = 0;
                    resolve(v)
                }
            });
        },
		getRefCmp: function (name) {
			if (this.$refs[name]) {
				if (uni.$u.test.array(this.$refs[name])) {
					return this.$refs[name][0];
				}
				return this.$refs[name];
			} else {
				return global.tempCmp[name]
			}
		},
        scanQrCode: function () {
			var vm = this;
            uni.scanCode({
                onlyFromCamera: true, //只能从相机中获取，不能从图片中获取
                success: function(res) { //获取扫码结果
					if (res.path) { // 小程序二维码
						var scene = decodeURIComponent(res.path.split('scene=')[1]);
						var sceneId = scene.split('$')[0];
						var value = scene.split('$')[1];
						vm.parseScene(sceneId, value, '扫码');
					} else {
						var result = res.result;
						if (result.split(':').length == 2) {
							vm.parseScene(result.split(':')[0], result.split(':')[1], '扫码');
						} else {
							uni.$u.toast('无效的二维码');
						}
					}
                   
                }, fail: function (res) {
                    uni.$u.toast('扫码失败');
                }
            });
        },
        gotoH5Page: function (url) {
            // #ifdef MP-WEIXIN
            global.listPageNeedReload = true;
            // #endif
            uni.navigateTo({ url: '/pages/openh5/index?url=' + encodeURIComponent(url) });
        },
        parseScene: function (key, value, type) {
            var vm = this;
            vm.waitVariable('globalConfig').then(() => {
                var sceneObj = vm.globalConfig.sceneConfig[key];
                if (!sceneObj) {
                    if (type) {
                        uni.$u.toast('无效的' + type);
                    }
                } else {
                    if (sceneObj.needLogin && !vm.hasLogin) {
                        vm.$refs.loginPopup.openCommonPopup();
                        vm.rememberAction = [sceneObj, value];
                        return;
                    } else {
                        vm.__parseScene(sceneObj, value);
                    }
                }
            })
        },
        onUserLogin: function () {
            if (this.rememberAction) {
                this.__parseScene(...this.rememberAction);
            }
            this.rememberAction = '';
            return;
        },
        __getFmtStr (str, n, preventIfNull) {
            var vm = this;
            let routes = getCurrentPages();
            let curParam = routes[routes.length - 1].options;
            return str.replace(/【([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*】/g, function (d) {
                var prop = d.slice(1, -1);
                if (prop == 'openId') {
                    return vm.openId;
                } else if (n[prop] || n[prop] == 0) {
                    return n[prop];
                } else {
                    return preventIfNull ? d : '';
                }
            }).replace(/《([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*》/g, function (d) {
                var prop = d.slice(1, -1);
                return vm.filterObject.queryObj[prop] || '';
            }).replace(/\{([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*\}/g, function (d) {
                var prop = d.slice(1, -1);
                return curParam[prop] || '';
            }).replace(/》([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*《/g, function (d) {
                var prop = d.slice(1, -1);
                return uni.getStorageSync(prop) || '';
            });
        },
        __parseScene: function (sceneObj, value) {
            var vm = this;
            if (sceneObj.url) {
                uni.navigateTo({ url: sceneObj.url + value });
            }
            if (sceneObj.h5) {
                uni.navigateTo({ url: '/pages/openh5/index?url=' + value });
            }
            if (sceneObj.api) {
                if (sceneObj.check) {
                    if (!global.scanItem || global.scanItem.id != value) {
                        uni.showModal({
                            title: '提示',
                            content: sceneObj.checkFailMsg || '二维码无效',
                            showCancel: false
                        });
                        return;
                    }
                }
                var apiUrl = vm.__getFmtStr(sceneObj.api, global.scanItem);
                function doRequest() {
                    uni.showLoading();
                    vm.getAndLoad('请求接口', apiUrl, function (res) {
                        uni.hideLoading();
                        uni.showModal({
                            title: '提示',
                            content: res.msg || (res.code == 0 ? '操作成功' : '操作失败'),
                            showCancel: false,
                            success: function(res3) {
                            }
                        });
                    });
                }
                if (sceneObj.apiBeforeTip) {
                    uni.showModal({
                        title: '提示',
                        content: sceneObj.apiBeforeTip || '是否确定操作',
                        showCancel: true,
                        success: function(res2) {
                            if(res2.confirm) { 
                                doRequest();
                            }
                            
                        }
                    });
                } else {
                    doRequest();
                }
            }
        }
    }
}